package com.hfzy.ihk.web.ivr.job.freeswitch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.web.ivr.biz.PushDataToEsBiz;
import com.hfzy.ihk.web.ivr.constant.RedisFields;
import com.hfzy.ihk.web.ivr.constant.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * @Auther: Administrator
 * @Date: 2019/3/1 10:21
 * @Description:
 */
@Component
@Profile({"pro","dev"})
public class PushDataEsJob {

    private static final Logger logger= LoggerFactory.getLogger(PushDataEsJob.class);

    private static Boolean isDataJobfinish = false;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PushDataToEsBiz pushDataToEsBiz;


    /**
     * 定期检查es推送失败的数据,进行重推,一分钟跑一次
     */
    @Scheduled(cron = "0 0/4 * * * ?")
    public  void  checkEsFailedData(){
        if(isDataJobfinish)
            return ;
        isDataJobfinish = true;
        try {

            //获取推送到es失败的通话记录的sessionId
            Set<String> pushFailedDataId = redisTemplate.opsForSet().members(RedisKey.PUSH_TO_ES_FAILED_HISTORY);

            logger.info("ivr>>>>>>>>>>>>>>>FreeswitchCall执行补推数据到Es redis 大小为：{}", pushFailedDataId.size());

            if (pushFailedDataId != null && !pushFailedDataId.isEmpty()) {

                for (String sessionid : pushFailedDataId) {
                    if (StringUtil.isEmpty(sessionid)) {
                        redisTemplate.opsForSet().remove(RedisKey.PUSH_TO_ES_FAILED_HISTORY, sessionid);
                    } else {
                        Map<String, String> callHistoryMap = redisTemplate.opsForHash().entries(RedisKey.CALL_HISTORY_RPIX + sessionid);
                        if (callHistoryMap == null || callHistoryMap.size() == 0) {
                            //假如为空,删除,免得堆积
                            redisTemplate.opsForSet().remove(RedisKey.PUSH_TO_ES_FAILED_HISTORY, sessionid);
                        } else {
                           // pushDataToEsTaskExecutor.execute(() -> {
                                pushDataToEsBiz.pushCallHistoryToEs(callHistoryMap.get(RedisFields.CALL_HISTORY_SESSION_ID), JSON.toJSONString(callHistoryMap), true);
                           // });
                        }
                    }
                }
            }
        }catch (Exception e){
            logger.error("ivr执行重推到es job异常",e);
        }
        isDataJobfinish=false;
    }

}
